﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace jQuery.Validation.DataAnnotations
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class CreditCardAttribute : ValidationAttribute
    {
        public CreditCardAttribute()
        {
        }

        public override bool IsValid(object value)
        {
            if (value == null)
                return true;

            string rootValue = value.ToString();

            Regex initialCheck = new Regex(@"[^0-9- ]+");

            if (initialCheck.IsMatch(rootValue))
                return false;

            Regex nonDigits = new Regex(@"\D");
            rootValue = nonDigits.Replace(rootValue, string.Empty);

            int nCheck = 0;
            bool bEven = false;

            for (int n = rootValue.Length - 1; n >= 0; n--)
            {
                var cDigit = rootValue[n];
                try
                {
                    int nDigit = int.Parse(cDigit.ToString());
                    if (bEven)
                    {
                        if ((nDigit *= 2) > 9)
                            nDigit -= 9;
                    }
                    nCheck += nDigit;
                    bEven = !bEven;
                }
                catch
                {
                    return false;
                }
            }

            return (nCheck % 10) == 0;
            
        }
    }
}
